//
//  HHYStockListVC.m
//  宝宝病例
//
//  Created by apple on 2019/6/10.
//  Copyright © 2019 apple. All rights reserved.
//

#import "HHYStockListVC.h"

#import "HHYHeader.h"

//V
#import "HHYPlaceHodlerView.h"


@interface HHYStockListVC ()<UITableViewDelegate, UITableViewDataSource>
{
    BOOL _showPlacehodlerView;//是否显示站位view
    HHYStockListVCType _type;
    int _currentPage;//当前页
    int _numOfPage;
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) HHYPlaceHodlerView *MYplaceHolderView;

@property (nonatomic, strong) UIView *footerView;

@end

@implementation HHYStockListVC

- (instancetype)initWithType:(HHYStockListVCType)type displayType:(HHYStockListTCellDisplayType)displayType shouldShowPlaceHodlerView:(BOOL)showPlaceHodlerView {
    self = [self init];
    if (self) {
        _taskModelArr = [NSMutableArray array];
        _showPlacehodlerView = showPlaceHodlerView;
        _displayType = displayType;
        _type = type;
        _currentPage = 0;
        _numOfPage = 20;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    [self setupNavi];
    
    
    
    if (_type == HHYStockListVCTypeMarket) {
        [self loadDataFormLocal];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.clearColor;
    
    [self createSubViews];
    
//    [self loadDataListFromServer];
    
    
//     [self loadDataListFromServer];
//    [self loadDataListFromServer_test];
    
    if (_type == HHYStockListVCTypeCustom) {
        [self setupMJ];
        
        [self.tableView.mj_header beginRefreshing];
    }

}

- (void)setupMJ {
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDataListFromServer)];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewDataListFromServer)];

}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = self.view.bounds;
    self.MYplaceHolderView.frame = CGRectMake(0, 0, self.tableView.xl_width*0.85, 180);
    self.MYplaceHolderView.center = self.tableView.center;
}

- (void)createSubViews {
    
    [self.view addSubview:self.tableView];
    
    if (_showPlacehodlerView) {
        [self.view addSubview:self.MYplaceHolderView];
    }
   
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

#pragma mark - tapGestureAction
- (void)tapGestureAction:(UITapGestureRecognizer *)tap {
    if (@available(iOS 11.0, *)) {
        //防止多次触发事件
        __block UIView *blockView = tap.view;
        blockView.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            blockView.userInteractionEnabled = YES;
        });
    }
    
    
}

#pragma mark - btnActions
- (void)btnActions:(UIButton *)btn {
    if (@available(iOS 11.0, *)) {
        //防止多次触发事件
        __block UIButton *blockBtn = btn;
        blockBtn.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            blockBtn.userInteractionEnabled = YES;
        });
    }
    
    
    //    if (self.sortView == btn) {
    //        self.sortView.selected = !self.sortView.selected;
    //        [self loadDataFormLocal];
    //        return;
    //    }
}

//  4.0
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(_type == HHYStockListVCTypeCustom) {
        return @[];
    }
    
    __weak typeof(self)wSelf = self;
    
    //删除
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        __strong typeof(self)sSelf = wSelf;
        //删除数据
        HHYStockDisplayModel *model = sSelf.taskModelArr[indexPath.row];
        
        // 本地
        NSString *mid = [NSString stringWithFormat:@"%@%@", [DGPUtil getCurrentUserID], model.symbol];
        NSString *order = [NSString stringWithFormat:@"where mid = \'%@\'", mid];
        
        NSArray *resArr = [HHYZXStockLocalModel findByCriteria:order];
        
        if (resArr.count > 0) {
            HHYZXStockLocalModel *localModel = [resArr firstObject];
            [localModel deleteObject];
        }
        
        [sSelf.taskModelArr removeObject:model];
        //更新数据源
        [sSelf.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
                               withRowAnimation:UITableViewRowAnimationFade];
    }];
    
    NSArray *actionArr = @[deleteAction];
    return actionArr;
}


#pragma mark - 加载网络数据
- (void)loadNewDataListFromServer  {
    _currentPage = 0;
    __weak typeof(self)wSelf = self;
    [HHYWebUtil requestStockListDataWithParameter:@{@"key":kJuHeAppKey, @"page":@(_currentPage), @"type":@1} successCallback:^(NSArray * _Nonnull datas) {
        __strong typeof(self)sSelf = wSelf;
        NSArray *dataArr = [HHYStockDisplayModel arrayOfModelsFromDictionaries:datas error:nil];
        sSelf.taskModelArr = [NSMutableArray arrayWithArray:dataArr];
        sSelf -> _currentPage++;
        dispatch_async(dispatch_get_main_queue(), ^{
            [sSelf.tableView reloadData];
            [sSelf.tableView.mj_header endRefreshing];
        });
    } failedCallback:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_header endRefreshing];
        });
        [HHYUtils textExampleLong:@"网络异常"];
    }];
}

- (void)loadMoreDataListFromServer {
//    //行情
//    if (_type == HHYStockListVCTypeCustom) {
//        NSArray *temArr = [[DGPUtil allDatas] subarrayWithRange:NSMakeRange(_currentPage++, _numOfPage)];
//        NSArray *dataArr = [HHYStockDisplayModel arrayOfModelsFromDictionaries:temArr error:nil];
//        [self.taskModelArr addObjectsFromArray:dataArr];
//        //第一次
//        if (_currentPage == 1) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.tableView reloadData];
//            });
//        } else {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.tableView reloadData];
//                    [self.tableView.mj_footer endRefreshing];
//                });
//            });
//        }
//        return;
//    }
    __weak typeof(self)wSelf = self;
    [HHYWebUtil requestStockListDataWithParameter:@{@"key":kJuHeAppKey, @"page":@(_currentPage), @"type":@1} successCallback:^(NSArray * _Nonnull datas) {
        __strong typeof(self)sSelf = wSelf;
        NSArray *dataArr = [HHYStockDisplayModel arrayOfModelsFromDictionaries:datas error:nil];
        [sSelf.taskModelArr addObjectsFromArray:dataArr];
        sSelf -> _currentPage++;
        dispatch_async(dispatch_get_main_queue(), ^{
            [sSelf.tableView reloadData];
            [sSelf.tableView.mj_footer endRefreshing];
        });
    } failedCallback:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
        });
        [HHYUtils textExampleLong:@"网络异常"];
    }];
   
}

- (NSArray *)arrayWithLocalModelArr:(NSArray *)localArr {
    NSMutableArray *temArr = [NSMutableArray array];
    
    for (HHYZXStockLocalModel *localModel in localArr) {
        HHYStockDisplayModel *model = [HHYStockDisplayModel new];
        model.symbol = localModel.symbol;
        model.name = localModel.name;
        model.trade = localModel.trade;
        model.changepercent =localModel.changepercent;
        model.buy = localModel.buy;
        model.sell = localModel.sell;
        
        [temArr addObject:model];
    }
    
    return temArr;
}

#pragma mark - 加载网络数据
- (void)loadDataListFromServer_test {
    NSArray *arr = [NSArray arrayWithContentsOfFile:@"/Users/apple/Desktop/新建文件夹/dataList.plist"];
    NSError *error;
    NSArray *modelArr = [HHYStockDisplayModel arrayOfModelsFromDictionaries:arr error:&error];
    
    if (!error) {
        self.taskModelArr = modelArr;
    }
    
    [self.tableView reloadData];
}

#pragma mark - 加载本地数据
- (void)loadDataFormLocal {
    // 本地
    NSString *order = [NSString stringWithFormat:@"where userID = \'%@\'", [DGPUtil getCurrentUserID]];
    
    NSArray *resArr = [HHYZXStockLocalModel findByCriteria:order];
    
    self.taskModelArr = [NSMutableArray arrayWithArray:[self arrayWithLocalModelArr:resArr]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)reloadData {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HHYStockListTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HHYStockListTCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.displayType = self.displayType;
    cell.stockModel = self.taskModelArr[indexPath.row];
    cell.hideAddBtn = (_type==HHYStockListVCTypeMarket);
    cell.separatorInset = UIEdgeInsetsZero;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //是否显示站位View
    if (_showPlacehodlerView) {
        self.MYplaceHolderView.hidden = !(self.taskModelArr.count == 0);
        self.footerView.hidden = !self.MYplaceHolderView.hidden;
    }
    return self.taskModelArr.count;
}

//- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    __weak typeof(self)wSelf = self;
//    //    //完成
//    //    UITableViewRowAction *finishAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Complete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//    //        __strong typeof(self)sSelf = wSelf;
//    //        // 完成
//    //        JNTMWawaJiLvModel *model = sSelf.taskModelArr[indexPath.row];
//    //        model.finished = YES;
//    //        model.keyWord = @"tsakId";
//    //        [model saveOrUpdate];
//    //        [sSelf.tableView reloadData];
//    //    }];
//
//    //删除
//    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        __strong typeof(self)sSelf = wSelf;
//        //删除数据
//        JNTMWawaJiLvModel *model = sSelf.taskModelArr[indexPath.row];
//        [model deleteObject];
//
//        NSMutableArray *temArr = [NSMutableArray arrayWithArray:sSelf.taskModelArr];
//        [temArr removeObject:model];
//        //更新数据源
//        sSelf.taskModelArr = temArr;
//        [sSelf.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
//                               withRowAnimation:UITableViewRowAnimationFade];
//        //4.0
//        sSelf.handler?sSelf.handler():nil;
//    }];
//
//    //判断返回action数组
//    JNTMWawaJiLvModel *model = self.taskModelArr[indexPath.row];
//
//    //    NSArray *actionArr = model.finished?@[deleteAction]:@[deleteAction, finishAction];
//    NSArray *actionArr = @[deleteAction];
//
//
//
//    return actionArr;
//}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

//- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//
//        //删除数据
//        JNTMWawaJiLvModel *model = self.taskModelArr[indexPath.row];
//        [model deleteObject];
//
//        NSMutableArray *temArr = [NSMutableArray arrayWithArray:self.taskModelArr];
//        [temArr removeObject:model];
//        //更新数据源
//        self.taskModelArr = temArr;
//        [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
//                              withRowAnimation:UITableViewRowAnimationFade];
//
//    }
//}

#pragma mark - 添加自选
- (void)marketAction {
    if (self.marketHandler) {
        self.marketHandler();
    }
}

#pragma mark - setter
- (void)setDisplayType:(HHYStockListTCellDisplayType)displayType {
    _displayType = displayType;
    dispatch_async(dispatch_get_main_queue(), ^{
       [self.tableView reloadData];
    });
}

#pragma mark - getter
- (HHYPlaceHodlerView *)MYplaceHolderView {
    if (!_MYplaceHolderView) {
        _MYplaceHolderView = [[HHYPlaceHodlerView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
        __weak typeof(self)wSelf = self;
        _MYplaceHolderView.hidden = YES;
        _MYplaceHolderView.addHandler = ^{
            __strong typeof(self)sSelf = wSelf;
            [sSelf marketAction];
        };
    }
    return _MYplaceHolderView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
//        _tableView.separatorColor = [UIColor clearColor];
        [_tableView registerNib:[UINib nibWithNibName:@"HHYStockListTCell" bundle:nil] forCellReuseIdentifier:@"HHYStockListTCell"];
        //        _tableView.rowHeight = 50;
        _tableView.estimatedRowHeight = 63;
        _tableView.rowHeight = 63;
        _tableView.tableFooterView = (_type == HHYStockListVCTypeCustom)?[[UIView alloc] initWithFrame:CGRectZero]:self.footerView;
    }
    return _tableView;
}

- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, hhy_kScreenWidth, 40)];
        
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        addBtn.frame = CGRectMake(0, 0, 150, 40);
        addBtn.xl_centerX = _footerView.xl_centerX;
        [addBtn setImage:[[UIImage imageNamed:@"tabbleView_添加"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [addBtn setTitle:@"添加自选" forState:UIControlStateNormal];
        [addBtn setTitleColor:rgba(255, 78, 19, 1) forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(marketAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_footerView addSubview:addBtn];
    }
    return _footerView;
}

@end
